// pages/user/user.js
import { Address } from './selAddress-model.js';

const app = getApp()
const $address = new Address()

Page({

  /**
   * 页面的初始数据
   */
  data: {
      userInfo: {},
      dialogShow:false,
      threeArea:{
        provice:null,
        city: null,
        area: null
      },
      hasCity:true,
      hasArea:true,
      editAddress:null,
      editRegion:[],
      addressList:null,
      isShowPopup:false,
      tips:'',
      toggleWord:'新增',
      editId:'',
      orderId: '',
      loadDone:false,
      editStatusReset:false//编辑状态判断是否改了省市区
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      console.log(options,options.orderId, options.addressId)
    let that = this
    let userInfo = wx.getStorageSync('userInfo')
    wx.showLoading({
        title: '加载中',
    })
   
    this.setData({
        userInfo: userInfo,
        orderId: options.orderId
    })
    let provice = {
            "data": {
                "pid": "0"
            }
        }
    
      // 获取省一级 pid 0
    $address.getThree(provice,res=>{
        if(res.status){
            that.setData({
                'threeArea.provice': res.data
            })
        } else {
            wx.hideLoading()
            $address.showMyTip({ _this: this, title: "服务器错误" })
        }
    })

    $address.getUserAddress({
        data:{
            "userId": (this.data.userInfo.id).toString()
        }
    },res=>{
        let status = res.status;
        let data = res.data;
        if(status){
            data && data.forEach(val=>{
                val.checked = false
            })
            if (options.addressId) {
                data.forEach((val,i)=>{
                    if (val.id == options.addressId){
                        val.checked = true
                    }
                })
            }
            that.setData({
                addressList: data,
                loadDone:true
            })
            wx.hideLoading()
        } else {
            wx.hideLoading()
            $address.showMyTip({ _this: this, title: "服务器错误" })
        }
    })
  },
  preventD(e){
      return;
  },
  // 省选择
  proviceChange(e){
    console.log(e.detail.value)
    let val = e.detail.value
    let provice = this.data.threeArea.provice[val]
    let that = this
    let params = {
        "data": {
            "pid": provice.id
        }
    }
    $address.getThree(params, res => {
        if (res.status) {
            that.setData({
                'threeArea.city': res.data,
                'editRegion[1]': '',
                'editRegion[2]': ''
            })
        }
    })
    this.setData({
        'editRegion[0]': {
            id: provice.pid,
            name: provice.name,
            index: val
        },
        hasCity: false,
        hasArea: true
    }) 
    if (this.data.toggleWord == '编辑') {
        this.setData({
            'editAddress.detailedAddress': '',
            editStatusReset:true
        })
    }
  },
  // 市选择
  cityChange(e) {
      console.log(e.detail.value)
      let that = this
      let val = e.detail.value
      let city = this.data.threeArea.city[val]
      let params = {
            "data": {
                "pid": city.id
            }
      }
      $address.getThree(params, res => {
          if (res.status) {
              that.setData({
                  'threeArea.area': res.data,
                  'editRegion[2]': '',
                  
              })
          }
      })
      this.setData({
          'editRegion[1]': {
              id: city.pid,
              name: city.name,
              index: val
          },
          hasArea: false
      })
      if (this.data.toggleWord == '编辑') {
          this.setData({
              'editAddress.detailedAddress': '',
              editStatusReset:true
          })
      }
  },
  // 区域选择
  areaChange(e) {
      console.log(e.detail.value)
      let val = e.detail.value
      let area = this.data.threeArea.area[val]
      
      this.setData({
          'editRegion[2]': {
              id: area.pid,
              name: area.name,
              index: val
          }
      })
      if (this.data.toggleWord == '编辑') {
          this.setData({
              'editAddress.detailedAddress': '',
              editStatusReset:true
          })
      }
  },
  // 设置默认地址
  setDefault(e){
    let id = e.currentTarget.dataset.id
    let that = this
    let params = {
        data: {
            "userId": "" + this.data.userInfo.id,
            "id": "" + id,
            "defaultOptions": "1"
        }
    }
    console.log(params)
    this.commonUpdate(params, '确认设置为默认地址吗？', '设置成功')
  },
  edit(e){
    let province, city, area;
    let id = e.currentTarget.dataset.id
    wx.showLoading({
        title: '加载中',
    })
    this.setData({
        'toggleWord':'编辑',
        'editId':id,
        editStatusReset:false
    })
    let parmas = {
        "data":{
            "id": id + ""
        }
    }
    // 省的请求后循环查找省的名称
    let provicePromise = new Promise((reslove,reject)=>{
        $address.getUserAddressById(parmas, res => {
            console.log(res)
            let data = res.data
            if (res.status) {
                console.log(res.data)
                // 当前的省市区id,给最上乘赋值
                province = data.province
                city = data.city
                area = data.area
                this.data.threeArea['provice'].forEach((val, i) => {
                    if (val.id == province) {
                        reslove(val.id)
                        this.setData({
                            editAddress: res.data,
                            'editRegion[0]': {
                                name: val.name,
                                index: i
                            }
                        })
                    }
                })
            }else{
                wx.hideLoading()                
                $address.showMyTip({ _this: this, title: "服务器错误" })   
            }
        })
    })
    // 请求后循环查找市的名称

    provicePromise.then(pRes=>{
        console.log('res22', pRes)
        let cityPromise = new Promise((reslove,reject)=>{
            // 获取市
            let cityParams = {
                "data": {
                    "pid": pRes
                }
            }
            $address.getThree(cityParams, cityRes => {
                if (cityRes.status) {
                    this.setData({
                        'threeArea.city': cityRes.data,
                    })
                    this.data.threeArea['city'].forEach((cityVal, cIdx) => {
                        if (cityVal.id == city) {
                            this.setData({
                                'editRegion[1]': {
                                    name: cityVal.name,
                                    index: cIdx
                                }
                            })
                            reslove(cityVal.id)
                        }
                    })
                } else {
                    wx.hideLoading()
                    $address.showMyTip({ _this: this, title: "服务器错误" })
                }
            })
        })
        // 请求后循环查找区域的名称
        cityPromise.then(aRes=>{
            console.log('33',aRes)
            let areaParams = {
                "data": {
                    "pid": aRes
                }
            }
            $address.getThree(areaParams, areaRes => {
                wx.hideLoading()
                if (areaRes.status) {
                    this.setData({
                        'threeArea.area': areaRes.data,
                    })
                    this.data.threeArea['area'].forEach((areaVal, aIdx) => {
                        if (areaVal.id == area) {
                            this.setData({
                                'dialogShow': true,                              
                                'editRegion[2]': {
                                    name: areaVal.name,
                                    index: aIdx
                                },
                                hasCity:false,
                                hasArea:false
                            })
                        }
                    })
                } else {
                    wx.hideLoading()
                    $address.showMyTip({ _this: this, title: "服务器错误" })
                }
            })
        })
    })
  },
  delete(e){
    let id = e.currentTarget.dataset.id
    let that = this
    let params = {
        data: {
            "userId": "" + this.data.userInfo.id,
            "id": "" + id,
            "status": "1"
        }
    }
    console.log(params)
    this.commonUpdate(params,'确定删除吗？','删除成功')
  },
  // 新增编辑地址
  formSubmit(e){
    console.log(e)
    let formdata = e.detail.value
    let that = this
    console.log(formdata)
    if (formdata.acceptName.trim() == '') {
        $address.showMyTip({ _this: this, title: "请输入收货人" })
    } else if (formdata.acceptName.length > 6) {
        $address.showMyTip({ _this: this, title: "收货人不超过6个字" })
    } else if (formdata.phone.trim() == '' || !/^((0\d{2,3}-\d{7,8})|(1[35847]\d{9}))$/.test(formdata.phone)) {
        $address.showMyTip({ _this: this, title: "请输入正确的联系电话" })
    } else if (formdata.area === '' || formdata.city === '' || formdata.provice === '') {
        $address.showMyTip({ _this: this, title: "请选择省市区县" })
    } else if (formdata.detail.trim() == '') {
        $address.showMyTip({ _this: this, title: "请输入详细地址" })
    } else if (formdata.detail.length > 50) {
        $address.showMyTip({ _this: this, title: "收货地址不超过50个字" })
    } else {
        let data = this.data
        let threeArea = data.threeArea
        console.log(threeArea.provice[formdata.provice].name,
            threeArea.city[formdata.city].name,
            threeArea.area[formdata.area].name)
        let PCA = threeArea.provice[formdata.provice].name + ' ' + threeArea.city[formdata.city].name + ' ' + threeArea.area[formdata.area].name + ' ' 
        if (data.toggleWord == '编辑' && !data.editStatusReset) {
            PCA = ''
        }
        let params = {
            data:{
                "userId": "" + data.userInfo.id,
                "province": "" + data.threeArea.provice[formdata.provice].id,
                "city": "" + data.threeArea.city[formdata.city].id,
                "area": "" +  data.threeArea.area[formdata.area].id,
                "detailedAddress": PCA+formdata.detail,
                "contacts": formdata.acceptName,
                "mobilePhone": formdata.phone
            }
        }

        console.log('params',params)
        wx.showModal({
            title: '提示',
            content: '确认保存吗？',
            success: function (res) {
                if (res.confirm) {
                    if(that.data.toggleWord == '编辑'){
                        params.data.id = data.editId
                        $address.updateUserAddress(params, res2 => {
                            console.log(res2)
                            let status = res2.status
                            if (status) {
                                wx.showToast({
                                    title: '编辑成功',
                                    icon: 'success',
                                    duration: 2000,
                                    success() {
                                        that.setData({
                                            dialogShow: false
                                        })
                                        setTimeout(()=>{
                                            let orderId = that.data.orderId
                                            that.onLoad({
                                                orderId
                                            })
                                        },2000)
                                    }
                                })
                            } else {
                                wx.hideLoading()
                                $address.showMyTip({ _this: that, title: "服务器错误" })
                            }
                        })
                    }else{
                        $address.addUserAddress(params,res3=>{
                            console.log('新增', res3)
                            let status = res3.status
                            if (status){
                                wx.showToast({
                                    title: '新增成功',
                                    icon: 'success',
                                    duration: 2000,
                                    success() {
                                        that.setData({
                                            dialogShow: false
                                        }) 
                                        setTimeout(() => {
                                            let orderId = that.data.orderId
                                            that.onLoad({
                                                orderId
                                            })
                                        }, 2000)
                                    }
                                })
                            } else {
                                wx.hideLoading()
                                $address.showMyTip({ _this: that, title: "服务器错误" })
                            }
                        })
                    }

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }
  },
  commonUpdate(params,content,title){
      var that = this
      wx.showModal({
          title: '提示',
          content: content,
          success: function (res) {
              if (res.confirm) {
                  $address.updateUserAddress(params, res2 => {
                      console.log(res2)
                      let status = res2.status
                      if (status) {
                          wx.showToast({
                              title: title,
                              icon: 'success',
                              duration: 2000,
                              success() {
                                  setTimeout(()=>{
                                    that.onLoad()
                                  },2000)
                              }
                          })
                      } else {
                          wx.hideLoading()
                          $address.showMyTip({ _this: this, title: "服务器错误" })
                      }
                  })
              } else if (res.cancel) {
                  console.log('用户点击取消')
              }
          }
      })
  },
  selAddress(e){
      let id = $address.getDataSet(e, "id")
      let data = this.data
      let that=this
      let addressList = data.addressList
      addressList.forEach((val,i)=>{
          if(val.id == id){
                val.checked = true
          }else{
              val.checked = false
              
          }
      })
      this.setData({
        addressList: addressList
      })

      let params = {
        "data": {
            "orderId": '' +data.orderId,
          "userAddressId": ''+id

        }
      }
      $address.updateOrderAddress(params,res=>{
        if(res.status){
          setTimeout(() => {
              var pagelist = getCurrentPages();
              if (pagelist.length > 1) {
                  //获取上一个页面实例对象
                  var prePage = pagelist[pagelist.length - 2];
                  prePage.getBackAddressId(id);

                  wx.navigateBack({
                      delta: 1
                  })
              }
            // wx.redirectTo({
            //   url: `/pages/orderConfirm/orderConfirm?orderId=${data.orderId}&addressId=${id}`,
            // })
          }, 500)
        }else{
          $address.showMyTip({ _this: that, title: "选择失败，请重新选择地址" })
        }
      });
     
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },
  showAddAddress(){
    this.setData({
        dialogShow: true,
        toggleWord:'新增',
        editAddress: null,
        editRegion: null,
        hasCity: true,
        hasArea: true
    })
  },
  save(){
    this.cancel()
  },
  cancel(){
    this.setData({
        dialogShow: false
    })
  },
  bindRegionChange(data){
    console.log(data)
    this.setData({
        'editRegion': data.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //this.onLoad()
    $address.getUserAddress({
        data: {
            "userId": (this.data.userInfo.id).toString()
        }
    }, res => {
        let status = res.status;
        let data = res.data;
        if (status) {
            this.setData({
                addressList: data,
            })
            wx.hideLoading()
            wx.stopPullDownRefresh()
        } else {
            wx.hideLoading()
            wx.stopPullDownRefresh()
            $address.showMyTip({ _this: this, title: "服务器错误" })
        }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})